package com.twm.drug.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 权限控制Shiro配置类
 */
@Configuration
public class ShiroFilterConfiguration {
    /**
     * 创建过滤工厂bean
     *
     * @return
     */
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean() {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager());
        /**
         * Shiro内置过滤器，实现权限相关的拦截器
         * anon:无需登录可以访问
         * authc:必须登录才可以访问
         */
        Map<String, String> filterMap = new LinkedHashMap<>();
        // 先put不需要权限的，后put登录之后才有权限访问的
        filterMap.put("/static/**", "anon");
        filterMap.put("/login", "anon");
        filterMap.put("/toLogin", "anon");
        // 需要登录之后才可以访问的
        filterMap.put("/**", "authc");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);
        // 不登陆自动转向的页面
        shiroFilterFactoryBean.setLoginUrl("/login");
        // 登录后，自动转向的页面
        shiroFilterFactoryBean.setSuccessUrl("/index");
        return shiroFilterFactoryBean;
    }

    /**
     * 权限管理
     *
     * @return
     */
    @Bean
    public DefaultWebSecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        // 登录权限认证
        securityManager.setRealm(userRealm());
        return securityManager;
    }

    /**
     * 创建Realm,认证用
     *
     * @return
     */
    @Bean
    public UserRealm userRealm() {
        return new UserRealm();
    }

    /**
     * thymeleaf整合Shiro
     *
     * @return
     */
    @Bean
    public ShiroDialect shiroDialect() {
        return new ShiroDialect();
    }
}
